package br.com.future;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.message.BasicHeader;

/**
 * SecurityContext is a singleton that holds all request/response information.
 * This object will be used by all interceptors/controllers
 *
 * @author Rafael Castanho Ferreira (mailto: rafa.ferreira@gmail.com)
 * @since 02-2011
 */
public class SecurityContext {

	private static final SecurityContext INSTANCE = new SecurityContext();

	/**
	 * Represents the list of headers from the original request as well as additional headers added by the interceptors.
	 */
	private List<Header> headers = new ArrayList<Header>();

	private SecurityContext() {
	}

	public static SecurityContext getInstance() {
		return INSTANCE;
	}

	/**
	 * Will add the given header. If the header already exists, then it will be updated with the new value.
	 * 
	 * @param name The name of the header to add or update.
	 * @param value The value of the header.
	 */
	public void addHeader(String name, String value) {
		addOrReplaceHeader(name, value, this.headers);
	}

	public List<Header> getHeaders() {
		return headers;
	}

	private void addOrReplaceHeader(String name, String value, List<Header> lstHeaders) {
		Header existingHeader = null;
		for (Header header : lstHeaders) {
			if (header.getName().equalsIgnoreCase(name)) {
				existingHeader = header;
				break;
			}
		}
		if (existingHeader != null) {
			lstHeaders.remove(existingHeader);
		}
		lstHeaders.add(new BasicHeader(name, value));
	}
}
